package com.simtop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.simtop.common.ServerResponse;
import com.simtop.controller.UserController;
import com.simtop.dao.CountDao;
import com.simtop.dao.OperateDao;
import com.simtop.dao.UserDao;
import com.simtop.pojo.Operate;
import com.simtop.pojo.User;
import com.simtop.service.JwtLoginService;
import com.simtop.util.JwtUtil;
import com.simtop.util.SHA256Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * JWT业务验证类
 */
@Service
public class JwtLoginServiceImpl implements JwtLoginService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private CountDao countDao;

    @Autowired
    private OperateDao operateDao;

    Logger logger = LoggerFactory.getLogger(JwtLoginServiceImpl.class);

    @Override
    public ServerResponse<String> login(User user) {




        //验证成功返回token
        User u = userDao.checkLoginNameOrEmail(user.getLoginName(),user.getEmail());
        if(u == null){
            return ServerResponse.createByErrorMsg("登录名不存在");
        }
        //如果登陆成功
        if(u.getPassword().equals(SHA256Util.generateShaPwd(user.getPassword())) && u.getRoleId().equals(user.getRoleId())){
            //使用JWT加密生成token todo
            //置空密码
            u.setPassword(StringUtils.EMPTY);
            // todo important token有效期24个小时
            String token = JwtUtil.sign(u,60*60*24*1000L);
            /**
             * todo 统计网站访问次数：登陆成功后统计次数变量count加1
             */
            int num = countDao.selectCount();
            int count = ++num;
            countDao.updateOne(count);
            /**
             * 记录日志文件
             */
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            logger.warn("登录时间:{} 登录id:{} 登录用户:{} ",simpleDateFormat.format(date),u.getId(),u.getUsername());


            user.setPassword(StringUtils.EMPTY);
            Operate operate = new Operate("后台用户登录",u.getUsername(),u.getRoleId(),"登录成功",new Date(), JSONObject.toJSONString(user));
            //登录成功后创建属于自己的文件夹 文件夹id = name C:\Users\刘昭博\Desktop
            //File file2=new File("C:\\Users\\刘昭博\\Desktop\\sjwjall\\" + user.getLoginName());
            //C:\webProject\front_page\SJWJ\sjwj_sj\file

            File file2=new File("C:\\webProject\\front_page\\SJWJ\\sjwj_sj\\file\\" + user.getLoginName());
            //String fil = "C:\\\\Users\\\\刘昭博\\\\Desktop\\\\sjwjall\\\\" + user.getLoginName();

            String fil = "C:\\\\webProject\\\\front_page\\\\SJWJ\\\\sjwj_sj\\\\file\\\\" ;
            //如果文件夹不存在
            if(!file2.exists()) {
                file2.mkdir();
                //创建文件夹
            }
            //判断文件是否存在

/*            File filetxt=new File("C:\\webProject\\front_page\\SJWJ\\sjwj_sj\\file\\" + user.getLoginName() + "\\stopwords.txt");
            //File filetxt=new File("C:\\Users\\刘昭博\\Desktop\\sjwjall\\" + user.getLoginName() + "\\stopwords.txt");

            if(!filetxt.exists()){
                try {
                    filetxt.createNewFile();
                    BufferedReader  br =  new BufferedReader(new InputStreamReader(new FileInputStream("C:\\webProject\\front_page\\SJWJ\\sjwj_sj\\file\\stopwords.txt"),"UTF-8"));
                    //BufferedReader  br =  new BufferedReader(new InputStreamReader(new FileInputStream("D:\\xtobject\\sjwj\\stopwords.txt"),"UTF-8"));
                    String b="";
                    StringBuffer sb = new StringBuffer();
                    while((b = br.readLine())!=null){
                        //得到文件内容放到sb中
                        sb.append(b+"\t\n");

                        //这里可以写自己想对每一行的处理代码
                    }

                    String s = sb.toString();
                    //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\刘昭博\\Desktop\\sjwjall\\"+ user.getLoginName() +"\\stopwords.txt"),"UTF-8"));
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\webProject\\front_page\\SJWJ\\sjwj_sj\\file\\"+ user.getLoginName() +"\\stopwords.txt"),"UTF-8"));
                    bw.write(s);
                    bw.flush();

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }*/




            operateDao.insertOperate(operate);
            return ServerResponse.createBySuccess(fil,token);
        }else if(!(u.getRoleId().equals(user.getRoleId()))){
            user.setPassword(StringUtils.EMPTY);
            Operate operate = new Operate("后台用户登录",u.getUsername(),u.getRoleId(),"登录失败,角色错误",new Date(), JSONObject.toJSONString(user));
            operateDao.insertOperate(operate);
            return ServerResponse.createByErrorMsg("角色错误");
        }
        Operate operate = new Operate("后台用户登录",u.getUsername(),u.getRoleId(),"登录失败,登录密码错误",new Date(), JSONObject.toJSONString(user));
        operateDao.insertOperate(operate);
        return ServerResponse.createByErrorMsg("登录密码错误");
    }




}
